#coding=utf-8
'''
Created on 2017-6-2

@author: sandy
'''

import socket
import select
import logging
import serverconfig
class Proxy(object):
    def __init__(self):
        self.route = {}
        pass

    def start(self,ip,port,maxclientcount = 512):
        self.proxy = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.proxy.bind((ip,port))
        self.proxy.listen(1)
        self.inputs = {self.proxy:None}
        self.serve_forever()

    def stop(self):
        self.on_quit()
        pass

    def serve_forever(self):
        logging.debug(u"listening")
        while 1:
            readable, _, _ = select.select(list(self.inputs.keys()), [], [])
            for self.sock in readable:
                if self.sock == self.proxy:
                    self.on_join()
                else:
                    try:
                        data = self.sock.recv(8192)
                    except Exception,e:
                        logging.error(str(e))
                        self.on_quit()
                        continue
                    if not data:
                        self.on_quit()
                    try:
                        self.route[self.sock].send(data)
                    except Exception, e:
                        logging.error(str(e))
                        self.on_quit()
                        continue


    def on_join(self):
        client, addr = self.proxy.accept()
        logging.info("proxy client " + str(addr) + 'connect')
        forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            forward.connect((serverconfig.instance.server_ip,serverconfig.instance.server_port))
        except Exception,e:
            logging.error(str(e))
            client.close()
            return
        self.inputs[client] = None
        self.inputs[forward] = None
        self.route[client] = forward
        self.route[forward] = client

    def on_quit(self):
        ls = [self.sock]
        if self.sock in self.route:
            ls.append(self.route[self.sock])
        for s in ls:
            if s in self.inputs:
                del self.inputs[s]
            if s in self.route:
                del self.route[s]
            s.close()

instance = Proxy()

if __name__ == "__main__":
    instance.start('',7901,1000)